//
//  TabarView.swift
//  Exchange
//
//  Created by rui on 2018/4/25.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class TabbarView: UIView {
    
    private(set) var selectIndex: Int = 0
    
    private let headerHeight: CGFloat = 40
    
    lazy private(set) var contentView: TabbarContentView = {
        let content = TabbarContentView(pages: self.pages, pageData: self.pageData)
        content.frame = CGRect(x: 0, y: headerHeight, width: self.width, height: self.height - headerHeight)
        content.delegate = self
        return content
    }()
    
    lazy private(set) var headerView: TabbarHeaderView = {
        let header = TabbarHeaderView(titles: self.titles,type: self.type)
        header.frame = CGRect(x: 0, y: 0, width: self.width, height: headerHeight)
        header.delegate = self
        return header
    }()
    
    var type: TabberHeaderType = .normal
    
    private var titles: [String]
    private var pages: [Any]
    
    private var pageData: [String:Any]?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init(titles: [String],pages: [String],pageData: [String:Any]? = nil, headerType: TabberHeaderType = .normal) {
        self.type = headerType
        self.titles = titles
        self.pages = pages
        self.pageData = pageData
        super.init(frame: CGRect.zero)
        initUI()
    }
    func initUI() {
        self.addSubview(contentView)
        self.addSubview(headerView)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        headerView.frame = CGRect(x: 0, y: 0, width: self.width, height: headerHeight)
        contentView.frame = CGRect(x: 0, y: headerHeight, width: self.width, height: self.height - headerHeight)
    }
    
    
    func fouce(selectIndex index: Int) {
        if index == selectIndex {
            return
        }
        selectIndex = index
        headerView.fouce(selectIndex: index, animated: true)
        contentView.layoutFouce(selectIndex: index)
    }
    
    func getCurPageController() -> TabbarPageController? {
        return contentView.getPageController(selectIndex: selectIndex)
    }
    
    func getPageControllers() -> [Any] {
        return contentView.pages
    }
}

extension TabbarView: TabbarContentViewDelegate, TabbarHeaderViewDelegate {
    
    func tabbarHeader(headerView: TabbarHeaderView, selectIndex: Int) {
        if self.selectIndex != selectIndex {
            self.selectIndex = selectIndex
            contentView.fouce(selectIndex: selectIndex)
        }
    }
    
    func tabbarContent(contentView: TabbarContentView, fromIndex from: Int, toIndex to: Int) {
        if from != to {
            self.selectIndex = to
            headerView.fouce(selectIndex: to, animated: true)
        }
    }
}
